<template>
  <el-drawer
    v-loading="drawer_loading"
    :before-close="handleClose"
    :size="'70%'"
    :title="title"
    :visible.sync="dialogFormVisible"
  >
    <div class="upload" style="overflow: auto; padding: 10px">
      <el-steps :active="active" finish-status="success">
        <el-step title="选择文件" />
        <el-step title="映射字段" />
        <el-step title="确认数据" />
      </el-steps>
      <div v-if="active == 0">
        <el-alert
          :closable="false"
          title="支持xlsx,xls格式，单次只可选择一个文件"
          type="info"
        />
        <el-upload
          action="#"
          class="upload-demo"
          :file-list="fileList"
          :on-change="beforeUpload"
        >
          <el-button type="primary">Click to upload</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传xlsx,xls文件</div>
          </template>
        </el-upload>
      </div>
      <div v-if="active == 1">
        <el-alert
          :closable="false"
          title="请将excel数据表的数据与系统数据进行匹配对应"
          type="info"
        />

        <el-form v-model="fieldArr" inline>
          <el-form-item
            v-for="(item, index) in fieldList"
            :key="index"
            :label="item.name"
          >
            <div v-if="item.optionList">
              <el-select
                v-model="fieldArr[item['key']]"
                clearable
                filterable
                placeholder="请选择对应的数据"
              >
                <el-option
                  v-for="(fieldData, fieldindex) in item.optionList"
                  :key="fieldindex"
                  :label="fieldData[item['optionLabel']]"
                  :value="fieldData[item['optionValue']]"
                />
              </el-select>
            </div>
            <div v-else>
              <el-select
                v-model="fieldArr[item['key']]"
                placeholder="请选择对应的数据字段"
              >
                <el-option
                  v-for="(fieldData, fieldindex) in excelData[fieldRow]"
                  :key="fieldindex"
                  :label="fieldData + '-' + fieldindex"
                  :value="fieldindex"
                />
              </el-select>
            </div>
          </el-form-item>
        </el-form>

        <el-form inline>
          <el-form-item label="数据结束行">
            <el-input v-model="lastRow" placeholder="确认数据结束行" />
          </el-form-item>
          <el-button type="primary" @click="configData">
            下一步，确认数据
          </el-button>
        </el-form>
        <!-- 将二维数组的数据展示出来，二维数组只有值，没有key，直接用循环的方式展示，不使用el-table,设置最宽行为row有多少列-->
        <table>
          <tr
            v-for="(item, index) in excelData"
            :key="index"
            style="padding: 0 4px"
          >
            <td>序号：{{ index }}</td>
            <td v-for="(item2, index2) in item" :key="index2">
              {{ item2 }}
            </td>
            <td>
              <el-radio v-model="fieldRow" :label="index">设为标题行</el-radio>
            </td>
          </tr>
        </table>
      </div>
      <div v-if="active == 2">
        <div style="text-align: right">
          <el-button type="primary" @click="active = 1">上一步</el-button>
          <el-button type="primary" @click="confirmData">
            确认导入下列数据
          </el-button>
        </div>
        <el-table :data="resultData">
          <el-table-column
            v-for="(item, index) in fieldList"
            :key="index"
            :label="item.name"
            :prop="item.key"
          />
        </el-table>
      </div>
    </div>
  </el-drawer>
</template>

<script>
  const XLSX = require('xlsx')
  export default {
    name: 'XlsxInput',
    props: {
      title: {
        type: String,
        default: '数据导入',
      },
      fieldList: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['successInputData'],
    data() {
      return {
        dialogFormVisible: false,
        active: 0,
        excelData: [],
        fieldRow: 0,
        fieldArr: {},
        lastRow: 0,
        resultData: [],
        drawer_loading: false,
      }
    },
    computed: {},
    methods: {
      show() {
        console.log('xlsx show')
        this.dialogFormVisible = true
        this.excelData = []
        this.fieldRow = 0
        this.active = 0
        console.log(this.fieldList)
      },
      configData() {
        let index = this.active
        const resultData = []
        for (index; index < this.lastRow; index++) {
          const element = this.excelData[index]
          // 遍历对象
          const tmp_obj = {}
          for (const key in this.fieldArr) {
            if (element[this.fieldArr[key]]) {
              tmp_obj[key] = element[this.fieldArr[key]]
            } else {
              tmp_obj[key] = ''
            }
          }
          console.log(tmp_obj)
          resultData.push(tmp_obj)
        }
        console.log(resultData)
        this.resultData = resultData
        this.active = 2
      },
      beforeUpload(file) {
        console.log(file)
        console.log(this.fieldList)
        const self = this
        return new Promise((resolve, reject) => {
          const reader = new FileReader()
          reader.onload = (e) => {
            const data = e.target.result
            const workbook = XLSX.read(data, { type: 'binary' })
            const sheetName = workbook.SheetNames[0] // 假设只有一个工作表

            const sheet = workbook.Sheets[sheetName]
            var excelData = XLSX.utils.sheet_to_json(sheet, { header: 1 })
            excelData = excelData.slice(0, 500);
            console.log(excelData)
            // 遍历第一行数据，看他名字与fieldList中的数据是否一致，如过一致，该列则为对应的字段数据列
            var _len = excelData[0].length;
  
            const fieldArr = {}
            for (let i = 0; i < _len; i++) {
              for (let j = 0; j < this.fieldList.length; j++) {
                if (excelData[0][i] == this.fieldList[j].name) {
                  fieldArr[this.fieldList[j].key] = i
                  break
                }
              }
            }
            this.fieldArr = fieldArr

            self.excelData = excelData
            self.active = 1
            self.lastRow = excelData.length

            // 在这里可以进一步处理excelData，例如将其发送到后端进行处理或显示在页面上
            resolve() // 表示文件上传成功
          }
          reader.onerror = (error) => {
            reject(error)
          }
          reader.readAsBinaryString(file.raw)
        })
      },
      confirmData() {
        this.$emit('successInputData', this.resultData) // 向父组件发送导入完成的数据
      },
      handleClose() {
        this.fileList = []
        this.picture = 'picture'
        this.allImgNum = 0
        this.imgNum = 0
        this.imgSuccessNum = 0
        this.imgErrorNum = 0
        /* if ("development" === process.env.NODE_ENV) {
          this.api = process.env.VUE_APP_BASE_API;
        } else {
          this.api = `${window.location.protocol}//${window.location.host}`;
        }

        this.action = this.api + this.url; */
        this.dialogFormVisible = false
      },
    },
  }
</script>

<style lang="scss" scoped>
  .upload {
    .upload-content {
      .el-upload__tip {
        display: block;
        height: 30px;
        line-height: 30px;
      }

      ::v-deep {
        .el-upload--picture-card {
          width: 128px;
          height: 128px;
          margin: 3px 8px 8px 8px;
          border: 2px dashed #c0ccda;
        }

        .el-upload-list--picture {
          margin-bottom: 20px;
        }

        .el-upload-list--picture-card {
          .el-upload-list__item {
            width: 128px;
            height: 128px;
            margin: 3px 8px 8px 8px;
          }
        }
      }
    }
  }
</style>
